<template>
  <div class="h-full flex flex-col overflow-auto">
    <a-card>
      <a-form ref="formRef" :model="formState" class="flex justify-between form-style-flex">
        <div class="flex">
          <a-form-item name="brName" class="w-[340px] mr-3 !mb-0">
            <SelectTable
              v-model:value="formState.brName"
              :search-params="{ stdate: formState.dateRange?.[0], eddate: formState.dateRange?.[1], type: '2' }"
              type="视光挂号患者列表"
              placeholder="销售单号/姓名/助记码/卡号/手机号/身份证号"
              @select="onSelect"
            />
          </a-form-item>
          <a-form-item label="挂号时间" name="dateRange" class="!mb-0">
            <a-range-picker v-model:value="formState.dateRange" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
          </a-form-item>
        </div>

        <div>
          <a-button style="margin: 0 8px" @click="onClickReset">重置</a-button>
          <a-button type="primary" @click="handleSearch">刷新</a-button>
        </div>
      </a-form>
    </a-card>
    <PatientInfoHeader :patient-info="selectItem" class="mt-2" @change="onClickReset">
      <a-divider type="vertical" :style="{ height: '40px', margin: '0 16px' }" />
      <div>
        <div class="flex items-center">
          <LabelValue label="卡号" :value="selectItem.brId" :width="180" label-class="w-[52px] text-right" />
          <LabelValue label="科室" :value="selectItem.ksmc" :width="180" />
          <LabelValue label="类别" :value="selectItem.ghlb" :width="180" />
        </div>
        <div class="flex items-center">
          <LabelValue label="门诊号" :value="selectItem.jzbh" :width="180" />
          <LabelValue label="医生" :value="selectItem.empName" :width="180" />
          <LabelValue label="时间" :value="selectItem.ghsj" :width="200" />
        </div>
      </div>
    </PatientInfoHeader>
    <div class="mt-2 flex flex-1 overflow-hidden">
      <div class="w-full flex flex-col overflow-auto h-full">
        <a-card class="w-full">
          <BaseTitle title="收费明细" class="!mb-2.5" />
          <div v-if="getSystemConfig('IS_OO_OPTICAN_SHOW_DISPOSE_CHANNEL') === '1'">
            <div class="flex justify-between items-center form-header py-2 rounded-t-lg mt-2">
              <p class="mb-0 ml-4 font-bold text-black mr-10">处置</p>
              <a-button type="primary" class="mr-4" @click="onClickDisDiscounts(1)">批量打折</a-button>
            </div>
            <div class="border px-4 py-4">
              <BaseTable :loading="loading" column-code="000524" :data-source="disposeTable" bordered>
                <template #bodyCell="{ column, index, record }">
                  <template v-if="column.dataIndex === 'xh'">
                    {{ index + 1 }}
                  </template>
                  <template v-if="column.dataIndex === 'xmmc'">
                    <template v-if="record.orderType === '1'">
                      <PopoverTable
                        :width="800"
                        :config="detailConfig"
                        :params="{ jzbh, orderType: [2], tcid: record.tcid, cfbh: record.cfbh, yzzt: 1, jfzt: 0 }"
                      >
                        <template #bodyCell="{ column: popColumn, record: popRecord }">
                          <template v-if="popColumn.dataIndex === 'xmmc'">
                            <MedicineInfo :value="{ mc: popRecord.xmmc, gg: popRecord.gg, cj: popRecord.cj }">
                              <template #suffix>
                                <a-badge v-if="popRecord?.insureFlag !== 1" count="自" class="ml-2" :number-style="{ backgroundColor: '#ff9540' }" />
                              </template>
                            </MedicineInfo>
                          </template>
                        </template>
                        {{ record?.xmmc }}
                      </PopoverTable>
                    </template>
                    <template v-else>
                      <MedicineInfo :value="{ mc: record?.xmmc, gg: record?.gg, cj: record?.cj }">
                        <template #suffix>
                          <a-badge v-if="record?.insureFlag === 0" count="自" class="ml-2" :number-style="{ backgroundColor: '#ff9540' }" />
                        </template>
                      </MedicineInfo>
                    </template>
                  </template>
                  <template v-if="column.dataIndex === 'yzzt'">
                    <a-tag v-if="!+record.yzzt" color="green">正常</a-tag>
                    <a-tag v-else color="red">失效</a-tag>
                  </template>
                  <template v-if="column.dataIndex === 'action'">
                    <a-button type="link" size="small" @click="onClickDisDiscounts(record)"> 打折 </a-button>
                  </template>
                </template>
              </BaseTable>
            </div>
          </div>

          <div v-for="(item, idx) in tableData" :key="idx" class="mb-4 mt-2">
            <div class="flex justify-between items-center form-header py-2 rounded-t-lg">
              <div class="flex">
                <p class="mb-0 ml-4 font-bold text-black mr-10">销售单 {{ item.doSaveOoOpticianRecordRequest?.id }}</p>
                <a-switch v-model:checked="item.checked" @click="onChecked" />
              </div>
              <div class="flex-1 flex items-center justify-start ml-20">
                <LabelValue label="经手人" :value="item.doSaveOoOpticianRecordRequest.handlerName" :width="200" />
                <LabelValue label="推荐医生" :value="item.doSaveOoOpticianRecordRequest.doctorName" :width="200" />
                <LabelValue label="预收款" :value="formatMoney(item.doSaveOoOpticianRecordRequest.downPaymentAmount)" value-class="text-red-600" :width="160" />
                <LabelValue label="取镜日期" :value="item.doSaveOoOpticianRecordRequest.takeTime" :width="200" />
                <LabelValue label="备注" :value="item.doSaveOoOpticianRecordRequest.memo" :width="300" />
              </div>
              <a-button type="primary" class="ml-12 mr-4" @click="onClickDiscounts(item, 1)">批量打折</a-button>
            </div>
            <div class="border px-4 py-4">
              <BaseTable :loading="loading" column-code="000282" :scroll="{ x: 1000 }" :data-source="item.list" bordered :row-class-name="getRowClass">
                <template #bodyCell="{ column, record }">
                  <template v-if="column.dataIndex == 'isOutside'">
                    <a-switch v-model:checked="record.isOutside" disabled :checked-value="'1'" :un-checked-value="'0'" />
                  </template>
                  <!--眼别   1：左眼 2：右眼 3：其他 -->
                  <template v-if="column.dataIndex == 'eyesType'">
                    <span v-if="record.eyesType == 1">左眼</span>
                    <span v-else-if="record.eyesType == 2">右眼</span>
                    <span v-else-if="record.eyesType == 3">其他</span>
                    <span v-else>/</span>
                  </template>
                  <!-- 类别 -->
                  <template v-if="column.dataIndex == 'payItemType'">
                    <span v-if="record.payItemType == 60">镜架费</span>
                    <span v-if="record.payItemType == 61 || record.payItemType == 62 || record.payItemType == 63">镜片费</span>
                    <span v-if="record.payItemType == 65 || record.payItemType == 64">视光其他</span>
                  </template>
                  <template v-if="column.dataIndex == 'payItemName'">
                    <div class="w-full h-full flex items-center cell-style" @click="onClick">
                      <div v-if="record?.mc" class="truncate" :title="record?.mc">{{ record?.mc }}</div>
                      <div v-if="record?.gg" class="text-gray-400 ml-2 text-xs">{{ record?.gg }}</div>
                      <div v-if="record?.cj" class="text-gray-400 ml-2 text-xs w-16 truncate">{{ record?.cj }}</div>
                    </div>
                  </template>
                  <template v-if="column.dataIndex == 'payStatus'">
                    <!-- 0：未缴费 1：已缴费 -->
                    <span v-if="record.payStatus === '1'">已缴费</span>
                    <span v-else style="color: rgb(0, 112, 240)">未缴费</span>
                  </template>
                  <template v-if="column.dataIndex === 'action'">
                    <a-button type="link" size="small" @click="onClickDiscounts(item, record)"> 打折</a-button>
                  </template>
                </template>
              </BaseTable>
            </div>
          </div>
        </a-card>
        <div class="flex flex-col relative w-full flex-1">
          <a-card class="mt-2 bottom-0 w-full sticky border-t h-full flex items-end justify-end">
            <div class="text-right mr-2 mb-2">
              <div class="my-2">
                本次应收 <span class="text-3xl text-red-500 font-bold">￥{{ formatAmount(medicalPrice.totalAmount) }}</span>
              </div>
              <a-button class="ml-2 w-28" size="large" @click="onClickReset">重置</a-button>
              <a-button type="primary" class="ml-2 w-28" size="large" :disabled="!formState.brName" ghost @click="openDeposit">收取定金</a-button>
              <a-button
                type="primary"
                class="ml-2 w-28"
                size="large"
                :disabled="!formState.brName || (tableDataId.length <= 0 && disposeTableId.length <= 0)"
                @click="onSuccessPreferential"
              >
                收费
              </a-button>
            </div>
          </a-card>
        </div>
      </div>
    </div>
    <!-- 定金 -->
    <ChargeOptician
      v-model:open="depositOpen"
      :is-discount="false"
      :is-dispose="false"
      :business-data="{ totalJe: depositNum, ysje: depositNum }"
      @success="onDepositSuccessPrice"
    />
    <!-- 收费 -->
    <ChargeOptician
      v-model:open="chargeOpen"
      :br-id="selectItem.brId"
      :jzbh="jzbh"
      :is-dispose="true"
      :business-data="{
        totalJe: medicalPrice.totalAmount,
        ysje: medicalPrice.payAmount,
        selectIds: tableDataId,
        yhje: medicalPrice.discountAmount,
        dzyh: medicalPrice.dzAmount
      }"
      :select-coupon="selectCoupon"
      source-type="2"
      @select="onChangeCoupons"
      @success="onSuccessPrice"
    />
    <!-- 视光打折 -->
    <DiscountsOne v-model:open="discountsOneOpen" :row-data="projectRow" @success="onDiscountsSuccess" />
    <DiscountsMany v-model:open="discountsManyOpen" :discounts-data="projectItem" @success="onDiscountsSuccess" />
    <!-- 处置打折 -->
    <DisDiscountOne v-model:open="disDiscountOneOpen" :row-data="projectRow" @success="onDisDiscountsSuccess" />
    <DisDiscountMany v-model:open="disDiscountManyOpen" :discounts-data="disposeTable" @success="onDisDiscountsSuccess" />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'
import BaseTitle from '@/components/BaseTitle'
import SelectTable from '@/components/SelectTable'
import { formatAmount } from '@/utils/format.js'
import { post } from '@/utils/request'
import { getSystemConfig } from '@/utils/systemConfig'
import ChargeOptician from '@/components/ChargeModal/ChargeOptician'
// import useUserStore from '@/store/user'
import DiscountsOne from './components/DiscountsOne'
import DiscountsMany from './components/DiscountsMany'
import DisDiscountOne from './components/DisDiscountOne.vue'
import DisDiscountMany from './components/DisDiscountMany.vue'

// const { empId } = useUserStore()
const chargeOpen = ref(false)
const depositOpen = ref(false)
const discountsOneOpen = ref(false)
const discountsManyOpen = ref(false)
const disDiscountOneOpen = ref(false)
const disDiscountManyOpen = ref(false)
const isCoupon = ref(true)
const isCharge = ref(true)
const isDeposit = ref(false)
const depositNum = ref(0)

const selectItem = ref({})
const disposeTable = ref([])
const tableData = ref({})
const tableDataId = ref([])
const tableDetailId = ref([])
const disposeTableId = ref([])
const projectRow = ref({})
const loading = ref(false)
const formState = ref({
  brName: '',
  dateRange: [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
})
const jzbh = ref('')
const categoryPrice = ref(0) // 实收金额
const formRef = ref(null)
const medicalPrice = ref({
  payAmount: 0
}) // 应收金额
const deposit = ref('')
const depositPrice = ref(0) // 押金金额
const projectItem = ref({})
const selectCoupon = ref({
  couponNo: [],
  couponAmount: 0,
  vipNo: '',
  opticianStatus: true,
  ids: [],
  detailIds: []
})

const onSelect = async (select) => {
  formState.value.brName = select.brName
  selectItem.value = select
  jzbh.value = select.jzbh
  deposit.value = ''
  getDisposeData()
  getTableData()
}
const getDisposeData = async () => {
  const { code, data, msg } = await post('/optometry/ooadolescentcheck/getOoOpticianRecordListSfCZ', {
    ooLsh: selectItem.value.jzbh,
    status: '1'
  })
  if (code !== 0) return message.error(msg)
  disposeTable.value = data || []
  disposeTableId.value = []
  disposeTable.value.forEach((item) => {
    disposeTableId.value = disposeTableId.value.concat([item.id])
  })
}
const getTableData = async () => {
  loading.value = true
  const { code, data, msg } = await post('/optometry/ooadolescentcheck/getOoOpticianRecordListSf', {
    ooLsh: selectItem.value.jzbh,
    status: '1'
  })
  loading.value = false
  if (code !== 0) return message.error(msg)
  if (data && data.length > 0) {
    tableData.value = []
    tableDetailId.value = []
    tableDataId.value = []
    data.forEach((item) => {
      item.list = item.list.map((it) => {
        return { mc: it.payItemName, gg: it.specification, ...it }
      })
      tableData.value.push({
        doSaveOoOpticianRecordRequest: item.ooOpticianRecordListResponse,
        list: item.list,
        checked: true
      })
      tableDataId.value.push(item.ooOpticianRecordListResponse.id)
      tableDetailId.value = tableDetailId.value.concat(item.list.map((it) => it.id))
    })
  } else {
    tableData.value = []
  }
  setSelectCoupon()
  const res = await post('/outp/mzdj/getDepositSlipListSgXsd', {
    brId: selectItem.value.brId,
    ids: tableDataId.value,
    status: '0'
  })
  if (res.code !== 0) return message.error(res.msg)
  if (res.data && res.data.length > 0) {
    deposit.value = res.data
      .map((item) => {
        return item.lsh
      })
      .join()
    depositPrice.value = res.data.reduce((total, currentValue) => {
      return total + currentValue.dpJe
    }, 0)
  }
  getAmount()
}

// 销售单单项/批量打折
const onClickDiscounts = async (row, record) => {
  if (record === 1) {
    discountsManyOpen.value = true
    projectItem.value = { ...row }
  } else {
    projectRow.value = { ...record, saleId: row.doSaveOoOpticianRecordRequest.id }
    discountsOneOpen.value = true
  }
}
// 处置单项/批量打折
const onClickDisDiscounts = async (row) => {
  if (row === 1) {
    disDiscountManyOpen.value = true
  } else {
    projectRow.value = { ...row, sjdj: row.dj, xmmc: row.mc }
    disDiscountOneOpen.value = true
  }
}
const onChangeCoupons = (e) => {
  selectCoupon.value.couponNo = e?.dyq
  selectCoupon.value.vipNo = e?.vip
  getAmount()
}
const getAmount = async () => {
  const { code, data, msg } = await post('/optometry/ooadolescentcheck/getOoOpticianRecordListAmount', {
    ooLsh: selectItem.value.jzbh,
    ids: tableDataId.value,
    couponsNo: selectCoupon.value.couponNo.length > 0 ? selectCoupon.value.couponNo.join(',') : '',
    vipNo: selectCoupon.value.vipNo
  })
  if (code !== 0) return message.error(msg)
  medicalPrice.value = data
}
// 单项/批量打折
const onDiscountsSuccess = async (params) => {
  const { code, msg } = await post('/optometry/ooadolescentcheck/doDiscount', {
    hjje: params.hjje,
    id: params.saleId,
    jsje: params.jsje,
    ooLsh: selectItem.value.jzbh,
    pwd: params.pwd,
    pzr: params.pzr,
    spids: params.spids,
    zkl: params.zkl
  })
  if (code !== 0) return message.error(msg)
  discountsOneOpen.value = false
  discountsManyOpen.value = false
  message.success(msg)
  getTableData()
}
const onDisDiscountsSuccess = async (params) => {
  const { code, msg } = await post('/outp/oupCharge/outpClinicalDiscount', { ...params, sfzsmx: 1 })
  if (code !== 0) return message.error(msg)
  disDiscountOneOpen.value = false
  disDiscountManyOpen.value = false
  message.success(msg)
  getDisposeData()
  getAmount()
}
//收费确定
const onSuccessPrice = async (params = {}) => {
  const { code, msg, data } = await post(
    params.zffs === '2' ? '/outp/oupCharge/doPaymentForScan' : '/outp/oupCharge/doSaveOutPFeeSg',
    {
      ...params,
      sflb: 'SG',
      ids: tableDetailId.value.concat(disposeTableId.value),
      xsIds: tableDataId.value,
      jzbh: jzbh.value,
      fbyh: params.fbwc,
      zjyh: params.zjyh,
      brId: selectItem.value.brId
    },
    {
      timeout: 2 * 60 * 1000 // 超时时间2分钟
    }
  )
  if (code !== 0) return message.error(msg)
  message.success(msg)
  chargeOpen.value = false
  selectItem.value = {}
  onPrint(data)
  onClickReset()
}
const formatZeroMoney = async () => {
  const { code, data } = await post('/outp/oupCharge/getChargeTypeList')
  if (code !== 0) return
  const chargeData = {}
  if (data && data.length > 0) {
    data.forEach((item) => {
      chargeData[item.zffsdm] = chargeData[item.zffsdm] ? chargeData[item.zffsdm] : 0
    })
  }
  chargeData.change = 0
  chargeData.yhje = 0
  chargeData.ysje = '0.00'
  chargeData.ssje = '0.00'
  onSuccessPrice(chargeData)
}
const onPrint = async (item = {}) => {
  if (getSystemConfig('OOS_PRINT_INVOICE_AFTER_CHARGE') === '0') return
  const { code, msg, data } = await post('/outp/oupCharge/PrintMedicareCharges', { jzbh: jzbh.value, pjhm: item.pjhm, sftfbs: '0' })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}

const onClickReset = () => {
  formState.value = {
    brName: '',
    dateRange: [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
  }
  jzbh.value = ''
  depositPrice.value = 0
  deposit.value = ''
  selectItem.value = {}
  tableData.value = []
  disposeTable.value = []
  categoryPrice.value = 0
  medicalPrice.value = {}
  selectCoupon.value = {
    couponNo: [],
    couponAmount: 0,
    vipNo: '',
    opticianStatus: true,
    ids: [],
    detailIds: []
  }
}
const handleSearch = () => {
  deposit.value = ''
  depositPrice.value = 0
  getAmount()
}
const onChecked = () => {
  tableDataId.value = []
  tableDetailId.value = []
  tableData.value.forEach((item) => {
    if (item.checked) {
      tableDataId.value.push(item.doSaveOoOpticianRecordRequest.id)
      tableDetailId.value = tableDetailId.value.concat(item.list.map((it) => it.id))
    }
  })
  depositPrice.value = 0
  deposit.value = ''
  setSelectCoupon()
  getAmount()
}
//获取分币优惠
// const getReceiptsAmount = async () => {
//   const { code, data, msg } = await post('/outp/oupCharge/getPennyDiscount', {
//     ysje: Number(medicalPrice.value.payAmount), //应收金额
//     yhje: 0, //优惠金额
//     patientCouponsId: couponId.value, // 优惠券id
//     chargeDepositlsh: [], // 押金单号
//     offsetAmount: 0 // 抵用券金额
//   })
//   if (code !== 0) return message.error(msg)
//   categoryPrice.value = data.ssje
// }
//点击收费
const onSuccessPreferential = async () => {
  const { code, msg } = await post('/outp/oupCharge/doCheckClinicalOrdersIsSign', {
    ids: tableDetailId.value.concat(disposeTableId.value)
  })
  if (code !== 0) return message.error(msg)
  if (!Number(formatAmount(medicalPrice.value.payAmount))) {
    formatZeroMoney()
  } else {
    chargeOpen.value = true
  }
}
const openDeposit = () => {
  depositNum.value = 0
  tableData.value.forEach((item) => {
    if (item.checked && (item.doSaveOoOpticianRecordRequest.chargeDepositStatus === '0' || item.doSaveOoOpticianRecordRequest.chargeDepositStatus === '2')) {
      depositNum.value += item.doSaveOoOpticianRecordRequest?.downPaymentAmount > 0 ? item.doSaveOoOpticianRecordRequest?.downPaymentAmount : 0
    }
  })
  if (depositNum.value > 0) {
    depositOpen.value = true
  } else {
    message.error('暂无要收的押金')
  }
}
//押金收取确定
const onDepositSuccessPrice = async (params) => {
  const ids = []
  tableData.value.forEach((item) => {
    if (
      item.checked &&
      item.doSaveOoOpticianRecordRequest.downPaymentAmount > 0 &&
      (item.doSaveOoOpticianRecordRequest.chargeDepositStatus === '0' || item.doSaveOoOpticianRecordRequest.chargeDepositStatus === '2')
    ) {
      ids.push(item.doSaveOoOpticianRecordRequest.id)
    }
  })
  const { code, msg } = await post(
    params.zffs === '2' ? '/outp/mzdj/doPaymentForScanYJ' : '/outp/oupCharge/saveDepositSlipSgSGSF',
    {
      sflb: 'SG',
      brId: selectItem.value.brId,
      dpJe: depositNum.value,
      ooLsh: jzbh.value,
      ...params,
      ooOpticianRecordLsh: ids
    },
    {
      timeout: 2 * 60 * 1000 // 超时时间2分钟
    }
  )
  if (code !== 0) return message.error(msg)
  message.success(msg)
  depositOpen.value = false
  getTableData()
}
const setSelectCoupon = () => {
  selectCoupon.value = {
    couponNo: [],
    couponAmount: 0,
    vipNo: '',
    opticianStatus: true,
    ids: [],
    detailIds: []
  }
  if (tableData.value && tableData.value.length > 0) {
    tableData.value.forEach((item) => {
      if (item.checked) {
        selectCoupon.value.couponNo.push(item.doSaveOoOpticianRecordRequest.couponsNo)
        selectCoupon.value.couponAmount += Number(item.doSaveOoOpticianRecordRequest.couponsJe)
        selectCoupon.value.vipNo = item.doSaveOoOpticianRecordRequest.vipNo
        selectCoupon.value.ids.push(item.doSaveOoOpticianRecordRequest.id)
        if (item.list?.length > 0) {
          item.list.forEach((it) => {
            selectCoupon.value.detailIds.push(it.id)
          })
        }
      }
    })
  }
}
const formatMoney = (val) => {
  return '￥' + formatAmount(val)
}
onMounted(() => {
  isCoupon.value = getSystemConfig('ENABLE_REGISTER_DISCOUNT') === '1' //启用挂号优惠功能
  isCharge.value = getSystemConfig('ENABLE_CHARGE_STANDARD_MODE') === '1' //收费标准
  isDeposit.value = getSystemConfig('CHARGE_DEPOSIT_ALLOW_AUTO_SELECT') === '1' //是否允许检索押金单
})
</script>
<style lang="less" scoped>
:deep(.ant-radio-button-wrapper) {
  flex: 1;
  color: var(--primary-color);
  text-align: center;
  border-color: var(--primary-color);
  &::before {
    background-color: var(--primary-color);
  }
}
.order-footer {
  @apply cursor-pointer border-b py-1;
}
:deep(.ant-tabs-content-holder) {
  overflow: hidden;
}
.discount-input {
  :deep(.ant-input) {
    text-align: right;
  }
}
.color-placeholder {
  color: var(--disabled-text-color);
}
.form-header {
  background-color: #f2f2f2;
}
</style>
